import java.io.*;
import java.net.*;
import java.util.*;

public class MF_ConnectionProcessor implements Runnable
{
  private MF_Server server;

  private Socket socket;

  private DataInputStream din;

  private DataOutputStream dout;

  private static String MF_url = "localhost";
  private static int MF_port = 2222;
  
  public MF_ConnectionProcessor( MF_Server server, Socket socket ) {
    this.server = server;
    this.socket = socket;

    new Thread( this ).start();
  }
  
  public void run() {
    try {
      InputStream in = socket.getInputStream();
      OutputStream out = socket.getOutputStream();

      din = new DataInputStream( in );
      dout = new DataOutputStream( out );

      int id = din.readInt();
      String dades = din.readUTF();
      
      System.out.println(dades);
      //Habrá que escribir dades en un archivo
      
      //Lanzamiento del experimento. Sólo pasamos el id como parámetro.
      List<String> command = new ArrayList<String>();
      command.add("/media/Datos/Documentos/PXC/Proyecto/Codis/hola.sh"); //Sustituir por path del script.
      command.add(Integer.toString(id));
      
      // Create and execute the new process 
      ProcessBuilder builder = new ProcessBuilder(command);
      // Redirects stderror to stdout
      builder.redirectErrorStream(true);
      Process process = builder.start();

      /*InputStream is = process.getInputStream();
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);
      String line;

      while ((line = br.readLine()) != null) {
         System.out.println(line);
       }*/

      try {
        socket.close();
      } catch( IOException ie2 ) {
        System.out.println( "Error closing socket "+socket );
      }

      server.removeConnection( this );

      System.out.println( "Closed connection from socket "+socket );
    }
    catch (Exception e){e.printStackTrace();}
  }

}
